package com.gitee.huanminabc.utils_common.multithreading.lock;

import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * @Description:
 * @Author huanmin
 * @Date 2024/6/5 下午1:31
 */
public interface LockBase  {
    void lock();

    boolean tryLock();

    boolean tryLock(long timeout, TimeUnit unit);

    void unlock();


    default <T> void lock(Runnable runnable) {
        lock();
        try {
            runnable.run();
        } finally {
            unlock();
        }
    }

    default <T> T lock(Supplier<T> supplier) {
        lock();
        try {
            return supplier.get();
        } finally {
            unlock();
        }
    }

    default <T> boolean tryLock(Runnable runnable) {
        if (tryLock()) {
            try {
                runnable.run();
                return true;
            } finally {
                unlock();
            }
        }
        return false;
    }

    default <T> T tryLock(T failResult, Supplier<T> supplier) {
        if (tryLock()) {
            try {
                return supplier.get();
            } finally {
                unlock();
            }
        }
        return failResult;
    }

    //时间
    default  boolean tryLock(long timeout, TimeUnit unit, Runnable runnable) {
        if (tryLock(timeout, unit)) {
            try {
                runnable.run();
                return true;
            } finally {
                unlock();
            }
        }
        return false;
    }

    default <T> T tryLock(long timeout, TimeUnit unit, T failResult, Supplier<T> supplier) {
        if (tryLock(timeout, unit)) {
            try {
                return supplier.get();
            } finally {
                unlock();
            }
        }
        return failResult;
    }
}
